package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.bellettini.BellettiniProductResDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class BellettiniProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;
    @Value("${bellettini.url}")
    private String bellettiniUrl;
    @Value("${bellettini.key}")
    private String bellettiniKey;
    @Value("${bellettini.type}")
    private String bellettiniType;

    public BellettiniProductResDTO getBellettiniProducts() {
        BellettiniProductResDTO bellettiniProductResDTO = null;
        try {
            //组装请求url
            StringBuilder sb = new StringBuilder();
            sb.append(bellettiniUrl);
            HttpHeaders headers = new HttpHeaders();
            headers.add("x-api-key", bellettiniKey);
            headers.add("Content-Type", bellettiniType);
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.exchange(sb.toString(), HttpMethod.GET, requestEntity, String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
//                String errorMessage = message.getString("error");
                log.info("--------------- bellettini获取商品列表异常{} ---------------", message);
            }
            ObjectMapper mapper = new ObjectMapper();
            bellettiniProductResDTO = mapper.readValue(response.getBody(), BellettiniProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bellettiniProductResDTO;
    }

}
